package jeye.midlet;

import java.util.Hashtable;

import javax.microedition.lcdui.Displayable;

import jeye.lcdui.CameraPreview;
import jeye.lcdui.CameraPreviewProperties;
import jeye.lcdui.EventsList;
import jeye.lcdui.MainMenu;
import jeye.lcdui.util.HttpServiceSupport;
import jeye.lcdui.util.ScreenFactorySupport;
import jeye.util.HttpConnector;

public class ScreenFactory {
	
	private ApplicationController controller;
	
	private HttpConnector connector;
	
	private Hashtable cachedScreens = new Hashtable();
	
	protected ScreenFactory(ApplicationController controller, HttpConnector connector) {
		this.connector = connector;
		this.controller = controller;
	}

	protected Displayable createScreen(int screenType) {
		ScreenFactorySupport screen = getScreenFromCache(screenType);
		
		if(screen == null) {
			screen = createNewScreen(screenType);
	
			if(screen != null) {
				if(screen instanceof HttpServiceSupport) {
					((HttpServiceSupport)screen).setHttpConnector(connector);
				}
				
				screen.setController(controller);
				screen.initialize();
				
				putScreenToCache(screenType, screen);
			}
		}
		
		return (Displayable)screen;
	}

	private ScreenFactorySupport createNewScreen(int screenType) {
		switch(screenType) {
			case ScreenType.MAIN_MENU:
				return new MainMenu();
			case ScreenType.EVENTS_LIST:
				return new EventsList();
			case ScreenType.PREVIEW:
				return new CameraPreview();
			case ScreenType.PREVIEW_PROPERTIES:
				return new CameraPreviewProperties();				
			default:
				return null;
		}
	}
	
	private ScreenFactorySupport getScreenFromCache(int screenType) {
		return (ScreenFactorySupport)cachedScreens.get(new Integer(screenType));
	}
	
	private void putScreenToCache(int screenType, ScreenFactorySupport screen) {
		cachedScreens.put(new Integer(screenType), screen);
	}
	
}
